//
//  XHRHomeViewController.m
//  快医
//
//  Created by 胥鸿儒 on 16/7/4.
//  Copyright © 2016年 xuhongru. All rights reserved.
//

#import "XHRHomeViewController.h"
#import "XHRTopView.h"
#import "XHRNetworkingToolManager.h"
#import "XHRWeatherItem.h"
#import <MJExtension.h>
#import "XHRScrollPictureView.h"
#import "XHRCategoryView.h"
#import "XHRPersonalMainPageViewController.h"
#import "XHRIllDetailViewController.h"
#import "JASidePanel.h"
#import "XHRScrollPictureView.h"
#import "WQCityTableVC.h"
#import "SYpublicViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface XHRHomeViewController ()<XHRScrollPictureViewDelegate,XHRTopViewDelegate,CLLocationManagerDelegate>
/**网络下载工具*/
@property(nonatomic,strong)XHRNetworkingToolManager *networkingManager;

/**图片轮播器URL地址数组*/
@property(nonatomic,strong)NSArray *pictureURLArray;

/**天气模型数组*/
@property(nonatomic,strong)NSMutableArray *weatherDataArray;

/**顶部天气view*/
@property(nonatomic,weak)XHRTopView *topView;

/**底部按钮分类view*/
@property(nonatomic,weak)XHRCategoryView *categoryView;

/**无线轮播View*/
@property(nonatomic,weak)XHRScrollPictureView *scrollPictureView;

@property (nonatomic,copy) NSString *location;

/**
 *  定位数据
 */
@property (nonatomic,strong) CLLocationManager *locManager;


@end

@implementation XHRHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //定位
    [self.locManager requestAlwaysAuthorization];
    [self.locManager startUpdatingLocation];
    
    [self initiateSettings];
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"location"]) {
        self.location = [[NSUserDefaults standardUserDefaults] objectForKey:@"location"];
    } else {
        self.location = @"上海";
    }
    
    [self setupData];
    
    self.topView.delegate = self;
 
    
}
#pragma mark -
#pragma mark - 初始化设置
- (void)initiateSettings
{
    self.navigationItem.title = @"马医一生";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage originalImageNamed:@"l"] style:UIBarButtonItemStyleDone target:self action:@selector(didClickLeftButton:)];
    
}

#pragma mark -
#pragma mark - 初始化数据
- (void)setupData
{
    
    NSMutableDictionary *pramDict = [NSMutableDictionary dictionary];
    pramDict[@"location"] = self.location;
    pramDict[@"output"] = @"json";
    pramDict[@"ak"] = @"17IvzuqmKrK1cGwNL6VQebF9";
    
    //MARK:发送天气网络请求
    [self.networkingManager GET:@"http://api.map.baidu.com/telematics/v3/weather" parameters:pramDict.copy progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        self.weatherDataArray = [XHRWeatherItem mj_objectArrayWithKeyValuesArray:[responseObject[@"results"] firstObject][@"weather_data"]];
        
   
        self.topView.weatherItem = self.weatherDataArray.firstObject;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"failure");
    }];
    
}


#pragma mark
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *loc = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
       
        CLPlacemark *placemark = placemarks[0];
        NSLog(@"%@",placemark.locality);
        
        if(placemark.locality){
            
            NSString *locCityStr = [NSString stringWithFormat:@"定位到当前位置:%@",[placemark.locality substringToIndex:[placemark.locality rangeOfString:@"市"].location]];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"定位提示" message:locCityStr preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //截取字符串赋值
                NSRange range = [placemark.locality rangeOfString:@"市"];
                NSString *place = [placemark.locality substringToIndex:range.location];
                [self setLocalStr:place];
                
            }];
            [alertController addAction:action];
            [self presentViewController:alertController animated:YES completion:nil];
        } else{
            NSLog(@"未获取到位置信息");
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"定位提示" message:@"未获取到位置信息,请检查网络" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:action];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
    }];
    
    [self.locManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位:%@",error);
}

#pragma mark
#pragma mark - 刷新天气数据
- (void)setLocalStr:(NSString *)localStr{
    _localStr = localStr;
    
    self.location = localStr;
    self.topView.localStr = localStr;
    
    [[NSUserDefaults standardUserDefaults] setObject:localStr forKey:@"location"];
    
    
    [self setupData];
}

#pragma mark
#pragma mark - city代理
- (void)pushCityVc{
    
    WQCityTableVC *cityTableVc = [[WQCityTableVC alloc] init];
    cityTableVc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:cityTableVc animated:YES];
}

#pragma mark -
#pragma mark - 监听按钮的点击
- (void)didClickLeftButton:(UIBarButtonItem *)sender
{
    JASidePanelController *sidePanelVC = (JASidePanelController *)XHRKeyWindow.rootViewController;
    [sidePanelVC showLeftPanelAnimated:YES];
}
#pragma mark -
#pragma mark -  viewDidLayoutSubviews
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self.topView makeConstraints:^(MASConstraintMaker *make) {
        make.top.trailing.leading.offset(0);
        make.height.equalTo(64);
    }];
    
    [self.categoryView makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.offset(0);
        make.height.equalTo(XHRScreenHeight * 0.55);
    }];
    
    [self.scrollPictureView makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.offset(0);
        make.top.equalTo(self.topView.bottom);
        make.bottom.equalTo(self.categoryView.top);
    }];
}
#pragma mark -
#pragma mark - scrollPictureView的代理方法
- (NSArray *)contentOfPictureInScrollPictureView
{
    return self.pictureURLArray;
}
#pragma mark -
#pragma mark - 懒加载
- (XHRScrollPictureView *)scrollPictureView
{
    if (!_scrollPictureView) {
        XHRScrollPictureView *scrollPictureView =[[XHRScrollPictureView alloc]init];
        scrollPictureView.delegate = self;
        _scrollPictureView = scrollPictureView;
        [self.view addSubview:scrollPictureView];
    }
    return _scrollPictureView;
}
- (XHRCategoryView *)categoryView
{
    if (!_categoryView) {
        XHRCategoryView *view = [[XHRCategoryView alloc]init];
        
        view.syblock = ^{
        
            SYpublicViewController *syctr=[[SYpublicViewController alloc] init];
            syctr.view.backgroundColor = [UIColor whiteColor];
            
            [self.navigationController pushViewController:syctr animated:YES];
        
        };
        
        __weak typeof(self)weakSelf = self;
        view.categoryViewBlock = ^(NSUInteger index,NSString *title){
            
        XHRIllDetailViewController *illDetailViewController =[[XHRIllDetailViewController alloc]init];
        illDetailViewController.index = index;
        illDetailViewController.illName = title;
        [weakSelf.navigationController pushViewController:illDetailViewController animated:YES];
        };
        _categoryView = view;
        [self.view addSubview:view];
    }
    return  _categoryView;
}
- (XHRTopView *)topView
{
    if (!_topView) {
        XHRTopView *topView = [[XHRTopView alloc]init];
        _topView = topView;
        [self.view addSubview:topView];
    }
    return _topView;
}
- (NSArray *)pictureURLArray
{
    if (!_pictureURLArray) {
        _pictureURLArray = @[
                                @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
                                @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
                                @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                                ];
    }
    return _pictureURLArray;
}
- (XHRNetworkingToolManager *)networkingManager
{
    if (!_networkingManager) {
        _networkingManager = [XHRNetworkingToolManager shareManager];
    }
    return _networkingManager;
}
- (NSMutableArray *)weatherDataArray
{
    if (!_weatherDataArray) {
        _weatherDataArray = [NSMutableArray array];
    }
    return _weatherDataArray;
}


- (CLLocationManager *)locManager{
    if(!_locManager){
        _locManager = [[CLLocationManager alloc] init];
        _locManager.delegate = self;
    }
    return _locManager;
}
@end
